package com.zhsj.OkeHomeConsumption.ui.activity.citypartner;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.bar.TitleBar;
import com.hjq.base.BaseDialog;
import com.hjq.dialog.DateDialog;
import com.hjq.dialog.MenuDialog;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.adapter.GridViewAddImgesAdpter;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.empty.CityPartnerShopBean;
import com.zhsj.OkeHomeConsumption.empty.EnterpriseRecruitBean;
import com.zhsj.OkeHomeConsumption.empty.MerchantTypeBean;
import com.zhsj.OkeHomeConsumption.empty.SelectCityEnity;
import com.zhsj.OkeHomeConsumption.empty.UpLoadImgBean;
import com.zhsj.OkeHomeConsumption.helper.GlideEngine;
import com.zhsj.OkeHomeConsumption.ui.activity.citypartner.mvp.BusinessLicensePresenter;
import com.zhsj.OkeHomeConsumption.ui.activity.citypartner.mvp.BusinessLicenseUIInterFace;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.ClearEditText;
import com.zhsj.OkeHomeConsumption.utils.UpLoadGridView;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/*
 *装企招募--完善信息--营业执照
 *
 * **/

public class BusinessLicenseActivity extends MyActivity implements BusinessLicenseUIInterFace {


    //营业执照
    @BindView(R.id.menliantu)
    UpLoadGridView menliantu;

    //注册号/统一社会\n信用代码
    @BindView(R.id.selet_daima)
    ClearEditText seletDaima;

    //名称
    @BindView(R.id.selet_name)
    ClearEditText seletName;

    //法定代表人/经    \n营者
    @BindView(R.id.selet_jingyingzhe)
    ClearEditText seletJingyingzhe;

    //经营场所/住所
    @BindView(R.id.selet_changsuo)
    ClearEditText seletChangsuo;


    @BindView(R.id.radio1)
    RadioButton radioSexMen;
    @BindView(R.id.radio2)
    RadioButton radioSexWomen;

    //营业执照有效期
    @BindView(R.id.radio)
    RadioGroup radio;

    //注册/成立时间
    @BindView(R.id.selet_createtimer)
    ClearEditText seletCreatetimer;

    //发证登记机关
    @BindView(R.id.selet_area)
    ClearEditText seletArea;

    //核准日期
    @BindView(R.id.selet_hezhuntimer)
    ClearEditText seletHezhuntimer;


    //注册资本
    @BindView(R.id.selet_zhuceziben)
    ClearEditText seletZhuceziben;

    //营业执照固定有效期
    @BindView(R.id.gudingyouxaioqi)
    TextView gudingyouxaioqi;

    private GridViewAddImgesAdpter menliantu_gridViewAddImgesAdpter;
    private List<UpLoadImgBean> menlian_imageServiceList;

    @BindView(R.id.btn_test_login)
    Button btnTestLogin;

    @BindView(R.id.tb_test_a_bar)
    TitleBar tb_test_a_bar;

    //经营类别id （用于获取主营业务）
    private int TypeId = -1;

    //门脸图 1  店内图2   营业执照3  许可证4 log5 背景6 店铺图7
    private int REQUEST_CODE_CHOOSE = -1;

    // 图片集合
    private List<File> datas_menlian = null;
    private List<UpLoadImgBean> imageServiceList = null;

    private BusinessLicensePresenter minePersonPresenter;

    private ArrayList<MerchantTypeBean> mMerchantTypeLists = null;
    private ArrayList<MerchantTypeBean> mMerchantChildTypeLists = null;

    private ArrayList<SelectCityEnity> mSelectCityLists = null;


    private int proviceId = -1;//省
    private int mcityId = -1;//市
    private int districCountryId = -1;//区
    private int streetId;//街道

    //营业执照是否长期有效0,否1.是
    private int businessLicenseLongterm = -1;


    private EnterpriseRecruitBean mCityPartnerShopbean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_businesslicense;
    }

    @Override
    protected int getTitleId() {
        return R.id.tb_test_a_bar;
    }

    @Override
    protected void initView() {
        minePersonPresenter = new BusinessLicensePresenter(getActivity(), this);
        Bundle bundle = getIntent().getExtras();
        tb_test_a_bar.setTitle("完善信息");
        mCityPartnerShopbean = (EnterpriseRecruitBean) bundle.getSerializable("CityPartnerShop");
        datas_menlian = new ArrayList<>();
        imageServiceList = new ArrayList<>();
        menlian_imageServiceList = new ArrayList<>();

        seletCreatetimer.setEnabled(true);
        seletCreatetimer.setInputType(InputType.TYPE_NULL);
        seletCreatetimer.setFocusableInTouchMode(false);
        seletCreatetimer.setFocusable(false);
        seletCreatetimer.setCursorVisible(false);

        seletHezhuntimer.setEnabled(true);
        seletHezhuntimer.setInputType(InputType.TYPE_NULL);
        seletHezhuntimer.setFocusableInTouchMode(false);
        seletHezhuntimer.setFocusable(false);
        seletHezhuntimer.setCursorVisible(false);

        menlian_imageServiceList.add(new UpLoadImgBean(mCityPartnerShopbean.getBusinessLicensePic()));
        seletDaima.setText(mCityPartnerShopbean.getBusinessLicenseCode());
        seletName.setText(mCityPartnerShopbean.getBusinessLicenseName());
        seletJingyingzhe.setText(mCityPartnerShopbean.getBusinessLicenseLegalEntity());
        seletChangsuo.setText(mCityPartnerShopbean.getBusinessLicenseAddress());
        seletCreatetimer.setText(mCityPartnerShopbean.getCompanyCreateTime());
        seletArea.setText(mCityPartnerShopbean.getBusinessLicenseFrom());
        seletHezhuntimer.setText(mCityPartnerShopbean.getBusinessLicenseCheckTime());
        seletZhuceziben.setText(mCityPartnerShopbean.getBusinessLicenseRegisterCapital());
        if (mCityPartnerShopbean.getBusinessLicenseLongterm() == 0) {
            businessLicenseLongterm = 0;
            gudingyouxaioqi.setEnabled(true);
            radioSexWomen.setChecked(true);
            gudingyouxaioqi.setText(mCityPartnerShopbean.getBusinessLicenseEffetiveTime());
        } else {
            businessLicenseLongterm = 1;
            gudingyouxaioqi.setEnabled(false);
            gudingyouxaioqi.setText("请选择营业执照上显示的准确有效期");
            radioSexMen.setChecked(true);
        }

    }

    @Override
    protected void initData() {
        menliantu_gridViewAddImgesAdpter = new GridViewAddImgesAdpter(menlian_imageServiceList, getActivity());
        menliantu_gridViewAddImgesAdpter.setMaxImages(2);
        menliantu.setAdapter(menliantu_gridViewAddImgesAdpter);
        menliantu.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                //营业执照
                REQUEST_CODE_CHOOSE = 1;

                ShootingDialog(REQUEST_CODE_CHOOSE, 1);
            }
        });
        radio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.radio1:
                        //长期有效
                        businessLicenseLongterm = 1;
                        gudingyouxaioqi.setEnabled(false);
                        gudingyouxaioqi.setText("请选择营业执照上显示的准确有效期");
                        break;
                    case R.id.radio2:
                        businessLicenseLongterm = 0;
                        gudingyouxaioqi.setEnabled(true);
                        break;

                }
            }
        });

    }


    private void submit() {

        if (menlian_imageServiceList.size() == 0) {
            toast("请上传营业执照");
            return;
        }

        String str_seletDaima = seletDaima.getText().toString();
        if (str_seletDaima.equals("")) {
            toast("请填写注册号/统一社会信用代码");
            return;
        }

        String str_seletName = seletName.getText().toString();
        if (str_seletName.equals("")) {
            toast("请填写名称");
            return;
        }

        String str_seletJingyingzhe = seletJingyingzhe.getText().toString();
        if (str_seletJingyingzhe.equals("")) {
            toast("请填写法定代表人/经营者");
            return;
        }

        String str_seletChangsuo = seletChangsuo.getText().toString();
        if (str_seletJingyingzhe.equals("")) {
            toast("请填写经营场所/住所");
            return;
        }

        if (businessLicenseLongterm == -1) {
            toast("请选择营业执照有效期");
            return;
        }
        String businessLicenseEffetiveTime = "";
        if (businessLicenseLongterm == 0) {
            if (businessLicenseEffetiveTime.equals("请选择营业执照上显示的准确有效期")) {
                toast("请选择营业执照有效期");
                return;
            }
        }

        String str_seletCreatetimer = seletCreatetimer.getText().toString();
        if (str_seletCreatetimer.equals("")) {
            toast("请填写注册/成立时间");
            return;
        }

        String str_seletArea = seletArea.getText().toString();
        if (str_seletArea.equals("")) {
            toast("请填写发证登记机关");
            return;
        }

        String str_seletHezhuntimer = seletHezhuntimer.getText().toString();
        if (str_seletHezhuntimer.equals("")) {
            toast("请选核准日期");
            return;
        }

        String str_seletZhuceziben = seletZhuceziben.getText().toString();
        if (str_seletZhuceziben.equals("")) {
            toast("请填写注册资本");
            return;
        }


        Map<String, Object> mapjson = new HashMap<>();
        mapjson.put("businessLicensePic", menlian_imageServiceList.get(0).getPhotoPath());//营业执照

        mapjson.put("businessLicenseCode", str_seletDaima);//统一社会信用代码

        mapjson.put("businessLicenseName", str_seletName);//mingche

        mapjson.put("businessLicenseLegalEntity", str_seletJingyingzhe);//请填写法定代表人/经营者

        mapjson.put("businessLicenseAddress", str_seletChangsuo);//经营场所/住所

        mapjson.put("businessLicenseEffetiveTime", businessLicenseEffetiveTime);//营业执照有效期 ,

        mapjson.put("businessLicenseLongterm", businessLicenseLongterm);//营业执照是否长期有效（0,否1.是）

        mapjson.put("businessLicenseRegisterTime", str_seletCreatetimer);//z注册/成立时间

        mapjson.put("businessLicenseFrom", str_seletArea);//发证登记机关

        mapjson.put("businessLicenseCheckTime", str_seletHezhuntimer);//请选核准日期

        mapjson.put("businessLicenseRegisterCapital", str_seletZhuceziben);//注册资本
        Intent intent = new Intent();
        // intent 依旧传递数据 put方法 ，区别在于，不需要指定页面跳转 如：Intent intent = new Intent(MainActivity.this, MainActivity2.class);
        intent.putExtra("map", (Serializable) mapjson);
        // 返回结果的特殊方法 setResult
        setResult(9, intent);
        // 必须调用该方法，结束当前页面
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    /**
     * 图片选择
     */
    private void Pictureselection(int code, int max) {
        if (code == 0) {
            EasyPhotos.createCamera(this)//参数说明：上下文
                    .setFileProviderAuthority("com.zhsj.OkeHomeConsumption.fileprovider")//参数说明：见下方`FileProvider的配置`
                    .start(101);
        } else {
            EasyPhotos.createAlbum(this, false, GlideEngine.getInstance())//参数说明：上下文，是否显示相机按钮，[配置Glide为图片加载引擎](https://github.com/HuanTanSheng/EasyPhotos/wiki/12-%E9%85%8D%E7%BD%AEImageEngine%EF%BC%8C%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%BA%93)
                    .setCount(max)//参数说明：最大可选数，默认1
                    .setPuzzleMenu(false)
                    .start(101);
        }

    }


    private String slipet(String list) {

        return StringUtils.strip(list.toString(), "[]");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == RESULT_OK) {
            //返回对象集合：如果你需要了解图片的宽、高、大小、用户是否选中原图选项等信息，可以用这个
            ArrayList<Photo> resultPhotos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);
            datas_menlian.clear();
            for (int i = 0; i < resultPhotos.size(); i++) {
                datas_menlian.add(uri2File(resultPhotos.get(i).path));
            }
            minePersonPresenter.UploadPost(datas_menlian);
        }
    }

    /**
     * 多张图片上传
     */
    @Override
    public void UploadPost(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONArray jsondata = jsonOBJ.optJSONArray("data");
                if (imageServiceList.size() != 0) {
                    imageServiceList.clear();
                }
                imageServiceList = new Gson().fromJson(jsondata.toString(), new
                        TypeToken<ArrayList<UpLoadImgBean>>() {
                        }.getType());
                if (imageServiceList != null && imageServiceList.size() > 0) {
                    switch (REQUEST_CODE_CHOOSE) {
                        case 1:
                            //门脸数据
                            for (int i = 0; i < imageServiceList.size(); i++) {
                                menlian_imageServiceList.add(imageServiceList.get(i));
                            }
                            menliantu_gridViewAddImgesAdpter.notifyDataSetChanged(menlian_imageServiceList);
                            break;
                    }
                    imageServiceList.clear();
                }
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            log("城市合伙人--- 多张图片上传");
        }
    }


    /**
     * user转换为file文件
     * 返回值为file类型
     *
     * @param uri
     * @return
     */
    private File uri2File(String uri) {
        File file = new File(uri);
        return file;
    }

    @OnClick({R.id.selet_createtimer, R.id.selet_hezhuntimer, R.id.gudingyouxaioqi, R.id.btn_test_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {


            case R.id.selet_createtimer:
                //成立时间
                //时间
                new DateDialog.Builder(this)
                        .setTitle("请选择日期")
                        .setListener(new DateDialog.OnListener() {
                            @Override
                            public void onSelected(Dialog dialog, int year, int month, int day) {
                                seletCreatetimer.setText(year + "-" + month + "-" + day);
                            }

                            @Override
                            public void onCancel(Dialog dialog) {
                            }
                        })
                        .show();
                break;
            case R.id.selet_hezhuntimer:
                //核准日期
                new DateDialog.Builder(this)
                        .setTitle("请选择日期")
                        .setListener(new DateDialog.OnListener() {
                            @Override
                            public void onSelected(Dialog dialog, int year, int month, int day) {
                                seletHezhuntimer.setText(year + "-" + month + "-" + day);
                            }

                            @Override
                            public void onCancel(Dialog dialog) {

                            }
                        })
                        .show();
                break;

            case R.id.gudingyouxaioqi:
                new DateDialog.Builder(this)
                        .setTitle("请选择日期")
                        .setListener(new DateDialog.OnListener() {
                            @Override
                            public void onSelected(Dialog dialog, int year, int month, int day) {
                                gudingyouxaioqi.setText(year + "-" + month + "-" + day);
                            }

                            @Override
                            public void onCancel(Dialog dialog) {

                            }
                        })
                        .show();
                break;

            case R.id.btn_test_login:
                //提交
                submit();
                break;
        }
    }

    @Override
    public void MerchantTypeGet(String context) {

    }

    private void ShootingDialog(final int code, final int max) {
        String[] arreaArr = getActivity().getResources().getStringArray(R.array.shooting_type);
        final List<String> shooting_type_list = Arrays.asList(arreaArr);
        new MenuDialog.Builder(this)
                .setCancel("取消") // 设置 null 表示不显示取消按钮
                //.setAutoDismiss(false) // 设置点击按钮后不关闭对话框
                .setList(shooting_type_list)
                .setListener(new MenuDialog.OnListener() {

                    @Override
                    public void onSelected(Dialog dialog, int position, String text) {
                        switch (position) {
                            case 0:
                                Pictureselection(position, max);
                                break;
                            case 1:
                                Pictureselection(position, max);
                                break;
                        }
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                        toast("取消了");
                    }
                })
                .setGravity(Gravity.BOTTOM)
                .setAnimStyle(BaseDialog.AnimStyle.BOTTOM)
                .show();
    }


}

